﻿#pragma once
#ifdef _WIN32
#include "wepoll.h"
#endif
#include "time_value.h"
#include "as_socket.h"
#include "base_type.h"
#include <mutex>
#include <memory>
#include <vector>
#include <functional>
#include <thread>

#ifdef _WIN32
typedef HANDLE EPOLL_FD;
#else
typedef int EPOLL_FD;
#endif


namespace as {
	namespace net {
		class Channel;
		class Poller;
		class EpollWatch : public std::enable_shared_from_this<EpollWatch>
		{
		public:
			typedef std::function<void()> TimerFun;
			struct EpTimer
			{
				std::time_t t_;
				TimerFun fun_;
				uint16 loop_ = 1;//Ä¬ÈÏÒ»´Î
				uint16 interval = 0;
			};

			EpollWatch();
			~EpollWatch();

			void UpdateChannel(Channel* channel);
			void RemoveChannel(Channel* channel);

			void WatchLoop();
			void Loop();


			EPOLL_FD GetEpFd() const { return epoll_fd_; }

			void ExceutePending(const TimeValue &tv, bool isExit = false);

			void AddTimer(TimerFun fun, int delay = 0, int loop = 1);

			void IsRunInLoop(TimerFun fun);
			bool IsLoopThread();

			void Exit();

			int GenerateConnId();
		private:
			std::shared_ptr<Poller> poller_;
			std::thread::id thread_id_;
			std::atomic<int> conn_id_;
			EPOLL_FD epoll_fd_;
			std::atomic<bool> isExit = false;
			bool isLoop = false;
			std::vector<EpTimer> pend_fun_;
			std::mutex loop_lock_;
		};

	}
}
